#include "qaddresourcedialog.h"
#include "ui_qaddresourcedialog.h"

#include "../../libs/sharedlib/qnamevalidator.h"
#include "../../libs/coreLib/qsoftcore.h"
#include "../../libs/sharedLib/qresourcemanager.h"

#include <QFile>
#include <QFileDialog>

QAddResourceDialog::QAddResourceDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QAddResourceDialog),
    m_nameEdit(new SHAREDLIB::QNameEdit("[_a-zA-Z0-9.]{,64}"))
{
    ui->setupUi(this);

    this->setProperty("no-ManhattanStyle",true);
    ui->horizontalLayout_2->addWidget(m_nameEdit,1);

    ui->floderCombo->setLineEdit(new SHAREDLIB::QNameEdit("[_a-zA-Z][_a-zA-Z0-9]{,64}"));

    SHAREDLIB::QResourceManager *manager=CORELIB::QSoftCore::getCore()->resourceManager();
    ui->floderCombo->addItems(manager->resourceFirstNames());
}

QAddResourceDialog::~QAddResourceDialog()
{
    delete ui;
}

void QAddResourceDialog::on_okBtn_clicked()
{
    SHAREDLIB::QNameEdit *edit=(SHAREDLIB::QNameEdit*)ui->floderCombo->lineEdit();
    QString firstName=edit->value();
    QString lastName=m_nameEdit->value();
    QString path=ui->filePath->text();

    if(firstName=="" || lastName=="" || !path.endsWith(".png"))
    {
        return;
    }

    QFile f(path);

    if(!f.exists())
    {
        return;
    }

    if(!f.open(QFile::ReadOnly))
    {
        return;
    }
    QByteArray array=f.readAll();

    SHAREDLIB::QResourceManager *manager=CORELIB::QSoftCore::getCore()->resourceManager();
    if(manager->resourceData(firstName,firstName+"/"+lastName).size()>0)
    {
        return;
    }
    manager->addResource(firstName,firstName+"/"+lastName,array);
    manager->save(QApplication::applicationDirPath()+"/resources/",firstName);
    close();
}

void QAddResourceDialog::on_cancelBtn_clicked()
{
   close();
}

void QAddResourceDialog::on_fileBtn_clicked()
{
    QString file=QFileDialog::getOpenFileName(this,tr("Resource File"),QDir::currentPath(),tr("Images (*.png)"));
    if(file!="")
    {
        file.replace("\\","/");
        ui->filePath->setText(file);
        int index=file.lastIndexOf("/");
        file=file.mid(index+1);
        m_nameEdit->setText(file);
    }
}
